//
//  SSSLoginViewController.m
//  SSSMerchant
//
//  Created by Darker on 2017/3/24.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSLoginViewController.h"
#import "SSSHomeViewController.h"
#import "SSSPersonCenterController.h"
#import "SSSMyIncomeViewController.h"
#import "SSSUserManager.h"
#import "SSSForgetPasswordViewController.h"
#import "SSSMerchantBenefitPagerController.h"
#import "APITool.h"

@interface SSSLoginViewController ()<UITextFieldDelegate>
{
    
    UIImageView *backImageView;// 放置注册界面的背景图的视图
    BOOL move;//记录文本框是否移动
    UIButton *loginBtn;//登陆按钮
    UIButton *forgetPasWordBtn;//忘记密码按钮
    ZDMyTextField *_textField;//文本框

}

/**
 *  装文本框的数组
 */
@property (nonatomic,strong)  NSMutableArray<UITextField *> *textFiledArray;

@end

@implementation SSSLoginViewController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    //self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建界面
    [self setInterfaceOfLogin];
}
- (void)setInterfaceOfLogin{
    
    
    UIImageView *bgImageView = [[UIImageView alloc]init];
    bgImageView.image = [UIImage imageNamed:@"bg"];
    bgImageView.userInteractionEnabled = YES;
    bgImageView.frame = self.view.frame;
    [self.view addSubview:bgImageView];
    
    backImageView = [[UIImageView alloc]init];
    backImageView.image = [UIImage imageNamed:@"icon_logo"];
    //backImageView.backgroundColor = [UIColor redColor];
    [bgImageView addSubview:backImageView];
    //约束
    backImageView.sd_layout
    .centerXEqualToView(bgImageView)
    .topSpaceToView(bgImageView,HeigthIos6CompeteWithCurrent(126))
    .widthIs(WidthIos6CompeteWithCurrent(75))
    .heightIs(HeigthIos6CompeteWithCurrent(78));
    
   UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor clearColor];
    [bgImageView addSubview:bgView];
    bgView.layer.borderColor = [UIColor colorWithHex:@"40B87B"].CGColor;
    bgView.layer.borderWidth = 1;
    bgView.sd_layout
    .topSpaceToView(backImageView,HeigthIos6CompeteWithCurrent(58))
    .leftSpaceToView(bgImageView,WidthIos6CompeteWithCurrent(43))
    .rightSpaceToView(bgImageView,WidthIos6CompeteWithCurrent(43))
    .heightIs(HeigthIos6CompeteWithCurrent(101));
    
    bgView.layer.cornerRadius = 20;
    bgView.layer.masksToBounds = YES;
    
    //横线
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = [UIColor colorWithHex:@"40B87B"];
    [bgView addSubview:lineView];
    lineView.sd_layout
    .centerYEqualToView(bgView)
    .leftSpaceToView(bgView,0)
    .rightSpaceToView(bgView,0)
    .heightIs(HeigthIos6CompeteWithCurrent(1));
    
    //textView
    // 占位文字的数组
    NSArray *placeHolders = @[@"请输入手机号",@"请输入密码"];
    // 装图片名字的数组
    NSArray *imageNamesArray = @[@"icon_phone",@"icon_password"];
    // 设置一个指针，指向文本框
    //UITextField *currentFiled = nil;
    SSSUserModel *user=[SSSUserManager getUserModel];
    for (int index = 0; index < placeHolders.count; index++) {
        
        _textField = [[ZDMyTextField alloc]init];
        [self.textFiledArray addObject:_textField];
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.delegate = self;
        _textField.backgroundColor = [UIColor clearColor];
        _textField.tag = 100 + index;
        _textField.font = [SSSFont systemFontOfSize:14];
        [bgView addSubview:_textField];
        _textField.placeholder = placeHolders[index];
        _textField.textColor = ThemeBlackColor;
        //  _textField.layer.borderWidth = 1;
        // _textField.layer.borderColor = [UIColor colorWithHex:@"A2A2A2"].CGColor;
        // 设置文本框的清楚按钮的模式
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        // 设置文本框的清楚按钮的模式
        _textField.clearsOnBeginEditing = YES;
        // 设置文本框的光标颜色
        _textField.tintColor = [UIColor colorWithHex:@"44b034"];
        [self setLfetView:imageNamesArray[index] isLeft:YES textField:_textField];
        
        //布局约束
        if (_textField.tag == 100) {
            _textField.text=user.phone;
            _textField.keyboardType = UIKeyboardTypePhonePad;
            _textField.sd_layout
            .leftSpaceToView(bgView,WidthIos6CompeteWithCurrent(15))
            .topSpaceToView(bgView,HeigthIos6CompeteWithCurrent(10))
            .heightIs(HeigthIos6CompeteWithCurrent(30))
            .rightSpaceToView(bgView,0);
        }else{
            _textField.text=user.password;
            _textField.sd_layout
            .leftSpaceToView(bgView,WidthIos6CompeteWithCurrent(15))
            .topSpaceToView(lineView,HeigthIos6CompeteWithCurrent(10))
            .heightIs(HeigthIos6CompeteWithCurrent(30))
            .rightSpaceToView(bgView,0);
            _textField.secureTextEntry = YES;
            
        }
        
    }
    //登陆按钮
    loginBtn = [[UIButton alloc]init];
    [loginBtn setBackgroundColor:[UIColor colorWithHex:@"40B87B"]];
    [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [SSSFont systemFontOfSize:16];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:loginBtn];
    
    //约束
    loginBtn.sd_layout
    .topSpaceToView(bgView,HeigthIos6CompeteWithCurrent(40))
    .leftEqualToView(bgView)
    .rightEqualToView(bgView)
    .heightIs(HeigthIos6CompeteWithCurrent(50));
    //切圆角
    loginBtn.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
    loginBtn.layer.masksToBounds = YES;
    
    //忘记密码按钮
    forgetPasWordBtn = [[UIButton alloc]init];
    [forgetPasWordBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetPasWordBtn setTitleColor:[UIColor colorWithHex:@"40B87B"] forState:UIControlStateNormal];
    [self.view addSubview:forgetPasWordBtn];
    [forgetPasWordBtn addTarget:self action:@selector(forgetPasWordClick:) forControlEvents:UIControlEventTouchDown];
    //按钮title文字居中
    forgetPasWordBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //设置文字大小
    forgetPasWordBtn.titleLabel.font = [SSSFont systemFontOfSize:15];

    //布局约束
    forgetPasWordBtn.sd_layout
    .topSpaceToView(bgView,HeigthIos6CompeteWithCurrent(0))
    .rightEqualToView(bgView)
    .widthIs(WidthIos6CompeteWithCurrent(70))
    .heightIs(HeigthIos6CompeteWithCurrent(40));

}
#pragma mark - 登陆按钮
- (void)loginBtnClick:(UIButton *)sender{
    
    [self doResignFirstResponder];
    
    NSString *messageNew = @"";
//    if (![SSSRegularExpression zd_isPhoneNumber:[self.textFiledArray[0] text]]) {
    if ([self.textFiledArray[0] text].length==0){
        messageNew = @"请输入手机号";
        
    }else if ([[self.textFiledArray[1] text] isEqualToString:@""]){
        
        messageNew = @"请输入密码";
        
    }if ([messageNew isEqualToString:@""]) {
        
     
        [self loginNetWithBlock:^(id responseObj) {
            NSLog(@"%@",responseObj);
            if (kResponseStatus==0) {
              
//                [QMUITips showLoading:@"登陆中..." inView:self.view hideAfterDelay:2];
                NSMutableDictionary *dict=[kResponseData mutableCopy];
                [dict setValue:[self.textFiledArray[0] text] forKey:@"phone"];
                  [dict setValue:[self.textFiledArray[1] text] forKey:@"password"];
                [SSSUserManager userInfoWithDict:dict.copy];//归档
                [self exhangeRootController];
            }
            else showTipHudStr(kResponseMessage);
        }];

    }else{

        showTipHudStr(messageNew)
        
    }
    
    //设置跟控制器
   //[MBProgressHUD hideHUDForView:self.view];
  
    
    //切换跟控制器
    //[self exhangeRootController];
    
}

#pragma mark - 切换跟控制器
- (void)exhangeRootController{

    SSSTabBarController *tabVc = [SSSTabBarController new];
    tabVc.tabBar.translucent = false;
    
    self.view.window.rootViewController = tabVc;
    
}
#pragma mark - 忘记密码按钮
- (void)forgetPasWordClick:(UIButton *)sender{
    
//    SSSForgetPasswordViewController *ForgetPasswordVc=  [[SSSForgetPasswordViewController alloc]init];
//    [self.navigationController pushViewController:ForgetPasswordVc animated:YES];
    SSSForgetPasswordViewController *ser =  [[SSSForgetPasswordViewController alloc]init];
    [self presentViewController:[[QMUINavigationController alloc]initWithRootViewController:ser] animated:YES completion:nil];
}
#pragma mark----UITextFieldDelegate回调方法
/**
 *  设置文本框的的左右视图
 *
 *  @param pictureName 视图图片名字
 *  @param isleft      是不是左边视图
 *  @param textField   具体的哪一个文本框
 */

- (void)setLfetView:(NSString *)pictureName isLeft:(BOOL ) isleft textField:(UITextField *)textField {
    
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *passImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:pictureName]];
    if (isleft) {
        textField.leftView = passImageView;
    }
    else {
        textField.rightView = passImageView;
    }
}
/**
 *  设置文本框的左视图
 */
- (void)setTextField:(UITextField *) textField andImageName:(NSString *) imageName{
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    textField.leftView = leftView;
}
/**
 *  点击空白处，让键盘消失
 *
 *  @param touches 手指触摸的地方
 *  @param event   手指触摸
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 让所有的文本框放弃第一响应者
    [self doResignFirstResponder];
    [self isMoveUp];
}

/**
 *  如果子视图已经向上移动的回调方法
 */
- (void)isMoveUp {
    if (move) {
        //        CGRect frame1 = button.frame;
        //        CGFloat y1 = frame1.origin.y;
        //        y1 += 100;
        //        frame1.origin.y = y1;
        //        button.frame = frame1;
        NSArray *subViewsArray = self.view.subviews;
        [subViewsArray enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect frame = obj.frame;
            CGFloat y = frame.origin.y;
            y += 100;
            frame.origin.y = y;
            obj.frame = frame;
        }];
        move = NO;
    }
}
/**
 *  让所有的文本框放弃第一响应者的回调方法
 */
- (void)doResignFirstResponder {
    [self.textFiledArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj resignFirstResponder];
    }];
}
/**
 *  懒加载，初始化数组
 *
 *  @return 返回一个初始化好的数组
 */
- (NSMutableArray *)textFiledArray {
    if (!_textFiledArray) {
        _textFiledArray = [NSMutableArray array];
    }
    return _textFiledArray;
}
#pragma mark -- 设置window的新根控制器、并记录账号/密码BOOL值
- (void)setupRootTabBarViewController
{
 
    if (self.button) {
        self.button();
    }
}

// 回调
- (void)SSSLoginViewControllerBlock:(SSSLoginViewControllerBlock)block{
    self.button = block;
}

#pragma mark - network
-(void)loginNetWithBlock:(void (^)(id responseObj))block{
NSDictionary *param=@{@"phone":[self.textFiledArray[0] text],@"password":[self.textFiledArray[1] text]};
      [QMUITips showLoading:@"登陆中..." detailText:nil inView:self.view];
//    [APITool urlStr:kLogin] 
    [ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kLogin) Parameters:param SuccessBlock:^(id response) {
    [QMUITips hideAllToastInView:self.view animated:YES];
    block(response);
    
} FailureBlock:^(NSError *error) {
     [QMUITips hideAllToastInView:self.view animated:YES];
    showTipHudStr(@"服务器异常");
} progress:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
